package com.fBlog.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.fBlog.dao.impl.AlphotoDaoI;
import com.fBlog.pojo.Talphoto;
import com.fBlog.pojo.Tuser;
import com.fBlog.pojo.User;
import com.fBlog.service.impl.PhotoServiceI;
import com.fBlog.service.impl.UserServiceI;

@Controller
@RequestMapping("/photoController")
public class PhotoController {

	@Autowired
	private PhotoServiceI photoService;
	
	@Autowired
	private AlphotoDaoI alphotoDao;

	@RequestMapping("/add")
	@ResponseBody
	public void add(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="name")String name,@RequestParam(value="userId")String userId) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//查询相册表中该用户下是否存在该相册名，存在则提示修改相册名，不存在则创建。
		Talphoto alphoto = alphotoDao.get("from Talphoto t where t.user.id = '"+userId+"' and t.name = '"+name+"'");
		if(alphoto!=null){
			writer.print("0");
		}else{
			writer.print("1");
			photoService.add(name,userId);
		}
	}
	
	/*
     * 上传多个文件
     */
    @RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8")
    public @ResponseBody void uploadFiles(HttpServletRequest request, HttpServletResponse response,@RequestParam("ipt") MultipartFile [] files) {
    	PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	//获取session中的用户信息
    	HttpSession session = request.getSession();
    	User user = (User)session.getAttribute("user");
    	//获取相册名
    	String alphotoId = request.getParameter("alphotoId");
    //	String path = "E:"+File.separator+"blog"+File.separator+"bg"+File.separator+"WebContent"+File.separator+"images"+File.separator+"albums"+File.separator;
    	String path = request.getServletContext().getRealPath(File.separator+"images"+File.separator+"albums")+File.separator;
    	//获取用户名和相册名作为该相册的文件夹。
    	String userName = user.getUserName();
    	String alphotoName = photoService.getAlphoto(alphotoId).getName();
    	String foldName = userName + "-" + alphotoName;
    	String foldPath = path+foldName;
    	//保证每个相册都存在相应的文件夹
    	File f = new File(foldPath);
    	if(!f.exists()){
    		f.mkdirs();
    	}
        String realPath;
        for(int i=0;i<files.length;i++){
            if (!files[i].isEmpty()) { 

                   String uniqueName=files[i].getOriginalFilename();//得到文件名
                   //获取图片后缀，限制只能上传图片格式：jpg，png，gif等，目前只允许上传这两种，以后可以再加格式。
                   String img = uniqueName.substring(uniqueName.lastIndexOf(".") + 1).trim().toLowerCase();
                   if(img.equals("jpg")||img.equals("png")||img.equals("gif")){
                	   realPath=foldPath+File.separator+uniqueName;//文件上传的路径这里为对应相册对应的文件夹
                    try {
   						files[i].transferTo(new File(realPath));
   					} catch (IllegalStateException e) {
   						// TODO Auto-generated catch block
   						e.printStackTrace();
   					} catch (IOException e) {
   						// TODO Auto-generated catch block
   						e.printStackTrace();
   					}   // 转存文件
                       
                       //保存图片信息
                       String code = photoService.addPhoto(uniqueName, alphotoId,foldName);
                      //上传成功标记"0"
                      writer.print(code);
                   }else{
                	 //图片格式错误标记"1"
                       writer.print("1");  
                   }
            }
        }
    }
	@RequestMapping("/saveName")
	@ResponseBody
	public void saveName(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="alphotoId")String alphotoId,@RequestParam(value="nowName")String nowName) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		String path = request.getServletContext().getRealPath(File.separator+"images"+File.separator+"albums")+File.separator;
		//获取用户名和相册名作为该相册的文件夹。
		String userName = user.getUserName();
		String alphotoName = photoService.getAlphoto(alphotoId).getName();
		String foldName = userName + "-" + alphotoName;
		//修改相册名称，给出相册id，修改后的名称，用户，项目路径，相册对应的文件名，因为要同步修改相册对应的文件名。
		String code = photoService.saveName(alphotoId,nowName,user,path,foldName);
		writer.print(code);
    }
	@RequestMapping("/deleteAlphoto")
	@ResponseBody
	public void deleteAlphoto(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="alphotoId")String alphotoId){
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		String path = request.getServletContext().getRealPath(File.separator+"images"+File.separator+"albums")+File.separator;
		//删除相册，包括该相册对应的文件夹及里面所有的照片
		String code = photoService.deleteAlphoto(alphotoId,user,path);
		writer.print(code);
    }

	@RequestMapping("/deletePhoto")
	@ResponseBody
	public void deletePhoto(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="photoIds")String photoIds){
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String path = request.getServletContext().getRealPath(File.separator+"images"+File.separator+"albums")+File.separator;
		//删除相片，包括该相片对应的文件夹里面的图片
		String code = photoService.deletePhoto(photoIds,path);
		writer.print(code);
	}
}

